#ifndef __2D_ARRAY_H__
#define __2D_ARRAY_H__

#include "Utils.h"

#ifndef NULL
#define NULL 0
#endif

//二维数组下标
struct TwoDIndex{ 
    int nX;
    int nY;
};

template <typename T>
class TwoDArray
{
    public:
        TwoDArray(int nWith, int nHeight){
            m_nWidth = nWith;
            m_nHeight = nHeight;
            m_pTList = NULL;
        }

        ~TwoDArray(){
            SAFE_DELETE_ARRAY(m_pTList);
        }

        bool Init(){
            int nSize = m_nWidth * m_nHeight;
            m_pTList = new T[nSize];
            if (!m_pTList){
                fprintf(stderr, "new fail, size:%d\n", nSize);
                return false;
            }
            return true;
        }

        inline T* Get(int nX, int nY){
            if (nX < 0 || nX >= m_nWidth || nY < 0 || nY >= m_nHeight){
                return NULL;
            }

            int nPos = (m_nWidth * nY) + nX; 
            return &(m_pTList[nPos]);
        }

        inline T* Get(TwoDIndex* pIndex) 
        {
            if (!pIndex){
                return NULL;
            }
            return Get(pIndex->nX, pIndex->nY);
        }

        inline void Set(int nX, int nY, T& v){
            if (nX < 0 || nX >= m_nWidth || nY < 0 || nY >= m_nHeight){
                return;
            }
            int nPos = (m_nWidth * nY) + nX; 
            m_pTList[nPos] = v; 
        }

//    private:
        int m_nWidth;
        int m_nHeight;
        T* m_pTList;  
};

#endif //__2D_ARRAY_H__
